//
//  DemoUpnpViewController.m
//  wAudioShare
//
//  Created by 赵帅 on 13-12-12.
//  Copyright (c) 2013年 赵帅. All rights reserved.
//

#import "DemoUpnpViewController.h"
#import "DemoUpnpCell.h"
#import "wis.h"
#import "WISInterfaces.h"
#import "pthread.h"
#import "DDFileLogger.h"
#import "Reachability.h"
#import "PersistableInfo.h"
#import "CustomIOS7AlertView.h"
#import "MulitySettingViewController.h"
#import "Utitlity.h"
#import "GlobalVar.h"
#import "ArchiveCoderRomoteDevice.h"

#import "SettingsViewController.h"

static const int ddLogLevel = LOG_LEVEL_VERBOSE;

@interface DemoUpnpViewController ()
<DemoUpnpDelegate,UIAlertViewDelegate,CustomIOS7AlertViewDelegate,UITextFieldDelegate,unConnectDevice>
{
    NSMutableArray * localArray;
    NSMutableArray * remoteArray;
    NSMutableArray * compareArray;
    BOOL reloadWithAnimation;
    BOOL canRefreshData;
    Reachability *wifiReach;
    
    UIView *customAlertView;
    UITextField *nameTextField;
    UITextField *userNameTextField;
    UITextField *passwordTextField;
    
    UIView *connectView;
    UITextField *connectUserNameTextField;
    UITextField *connectPassWordTextField;
    
    NSString *ipUrl;
    
    NSString *changeStr;
}

@property (assign) IBOutlet UITableView * tableView;
@property (retain) NSIndexPath * currentSelected;
@property (retain) NSIndexPath * lastSelected;

@end

@implementation DemoUpnpViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    wifiReach = [Reachability reachabilityForLocalWiFi];
    
    // Do any additional setup after loading the view from its nib.
    DDLogVerbose(@"%s", __FUNCTION__);

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = UITextAlignmentCenter;
    titleLabel.text = @"Show Home";
    self.navigationItem.titleView = titleLabel;
    
    reloadWithAnimation = NO;
    
    localArray = [[NSMutableArray alloc] init];
    
    double delayInSeconds = 0.5;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self refreshUpnpStatus];
    });
    
    
    UILabel *deviceUUIDLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 0, 0)];
    deviceUUIDLabel.textAlignment = NSTextAlignmentCenter;
    deviceUUIDLabel.text = [[GlobalInfo sharedInstance] getUniqueID];
    deviceUUIDLabel.font = [UIFont systemFontOfSize: [UIFont smallSystemFontSize]];
    deviceUUIDLabel.textAlignment = UITextAlignmentCenter;
    deviceUUIDLabel.textColor = [UIColor blackColor];
    deviceUUIDLabel.backgroundColor = [UIColor clearColor];
    deviceUUIDLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [deviceUUIDLabel sizeToFit];
    deviceUUIDLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, deviceUUIDLabel.bounds.size.width, deviceUUIDLabel.bounds.size.height)];
    headerView.backgroundColor = [UIColor clearColor];
    [headerView addSubview:deviceUUIDLabel];
    
    self.tableView.tableHeaderView = headerView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    canRefreshData = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    canRefreshData = NO;
}

#pragma mark - navigation methods


-(IBAction)backButtonPressed:(id)sender
{
    double delayInSeconds = 0.1;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self.navigationController popViewControllerAnimated:YES];
    });
}

#pragma mark -
#pragma mark UITableView Delegate & Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return [[GlobalInfo sharedInstance].remoteArray count];
    }
    else
    {
        return [localArray count];
    }
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    DemoUpnpCell *cell = (DemoUpnpCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell =  [[[NSBundle mainBundle] loadNibNamed:@"DemoUpnpCell" owner:self options:nil] objectAtIndex:0];
    }
    
    // Configure the cell.

    cell.delegate = self;
    
    if(self.currentSelected != nil && self.currentSelected.row == indexPath.row && self.currentSelected.section == indexPath.section)
    {
        [cell expand:YES withAnimation:reloadWithAnimation];
        
        if(indexPath.section == 0)//remote
        {
            [cell isConnected:reloadWithAnimation];
        }
        else
        {
            [cell isDisConnected:reloadWithAnimation];
        }
        reloadWithAnimation = NO;
    }
    else if(self.lastSelected != nil && self.lastSelected.row == indexPath.row && self.lastSelected.section == indexPath.section)
    {
        [cell expand:NO withAnimation:YES];
        
        [cell hideAll];
    }
    
    if(indexPath.section == 0)//remote
    {
        cell.ipLabel.text = nil;
        cell.changeDeviceNameBtn.enabled = NO;
        
        NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:indexPath.row];
        wis_user_dev device;
        [value getValue:&device];
        
        NSString *nameStr = [[NSString alloc] initWithCString:device.name encoding:NSUTF8StringEncoding];
        cell.contentLabel.text = nameStr;
        NSString *deviceString = [NSString stringWithUTF8String:device.uuid];
        NSLog(@"cell nameStr: %@", nameStr);
        
        for (NSDictionary *dic in [GlobalInfo sharedInstance].upnpArray)
        {
            //NSLog(@"cell %@", dic.description);
            
            if ([dic[@"uuid"] isEqualToString:deviceString])
            {
                NSString *baseString = dic[@"baseURL"];
                if (baseString)
                {
                    NSURL *url = [NSURL URLWithString:baseString];
                    cell.ipLabel.text = url.host;
                    cell.changeDeviceNameBtn.enabled = YES;
                    cell.changeDeviceNameBtn.alpha = 1.0;
                }
            }
        }
        
        cell.changeDeviceNameBtn.enabled = YES;
        
        cell.uuidLabel.text = [NSString stringWithFormat:@"%s",device.uuid?device.uuid:""];
        [cell setStatus:device.status withVersion:0];
        
#warning 暂时设置DeviceNameBtn
        #if TARGET_IPHONE_SIMULATOR
        {
        cell.changeDeviceNameBtn.enabled = YES;
        cell.changeDeviceNameBtn.alpha = 1.0;
        }
        #endif
    }
    else//upnp
    {
        NSDictionary * dic = [localArray objectAtIndex:indexPath.row];
        NSLog(@"cell %@", dic.description);
        //add by anson
        cell.uuidLabel.text = [dic objectForKey:@"uuid"];
        
        NSString *namStr = [dic objectForKey:@"ssid"];
        //const char *c = [namStr cStringUsingEncoding:NSISOLatin1StringEncoding];
        //NSString *new = [[NSString alloc] initWithCString:c encoding:NSUTF8StringEncoding];
        
        cell.contentLabel.text = namStr;
        NSLog(@"cell %@", namStr);
        NSString * baseURL = [dic objectForKey:@"sendBaseURL"];
        DDLogVerbose(@"%s UPNP cell  %@", __FUNCTION__ , dic.description);
        if (baseURL)
        {
            //add by anson 5.23 email
            NSURL *url = [NSURL URLWithString:baseURL];
            cell.ipLabel.text = url.host;
//            [cell.remoteControlButton setTitle:@"局域网控制" forState:UIControlStateNormal];
        }
        cell.changeDeviceNameBtn.hidden = YES;
        
        if ([[dic objectForKey:@"bigVersion"] intValue] < 2) {
            [cell.remoteControlButton setAlpha:0];
        }
        [cell setStatus:-1 withVersion:[[dic objectForKey:@"bigVersion"] intValue]];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.currentSelected != nil && indexPath.row == self.currentSelected.row && indexPath.section == self.currentSelected.section)
        return 90;
    else
        return 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return @"已关联设备";
    }
    else
    {
        return @"未关联设备";
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    if (indexPath.section == 0)
    {
        NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:indexPath.row];
        wis_user_dev device;
        [value getValue:&device];
    }
    else
    {
        NSDictionary * value = [localArray objectAtIndex:indexPath.row];
        NSString *deviceString = value[@"uuid"];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:deviceString forKey:@"localDevice"];

    }
    
    DemoUpnpCell * cell = (DemoUpnpCell *)[tableView cellForRowAtIndexPath:indexPath];

    [self animateExpandMethod:cell];
}

#pragma mark - DemoCell delegate
-(void)expandButtonPressed:(DemoUpnpCell *)cell
{
    [self animateExpandMethod:cell];
}

-(void)connectButtonPressed
{
    NSLog(@"connectButtonPressed");
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    alertView.tag = 20000;
    alertView.delegate = self;
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消",@"确定", nil]];//添加按钮
    [alertView setContainerView:[self connectWithAlertView:connectView]];
    [alertView show];
}

- (void)connected
{
    if(self.currentSelected.row >= [localArray count]) return;
    
    @synchronized(localArray)
    {
        NSDictionary * dic = [localArray objectAtIndex:self.currentSelected.row];
        
        [WISInterfaces wis_send_bind_cmd:[GlobalInfo sharedInstance].m_CmdSock uuid:(char *)[[dic objectForKey:@"uuid"] UTF8String]];
        
        {
            NSLog(@"- (void)connected %@", dic.description);
            wis_user_dev device;
            const char *name =[dic[@"ssid"] UTF8String];
            memcpy(device.name, name, 32);

            const char *deviceUUID =[dic[@"uuid"] UTF8String];
            memcpy(device.uuid, deviceUUID, 32);

            //const char *deviceBindTime =[dic[@"uuid"] UTF8String];
            //memcpy(device.bind_time, deviceBindTime, 20);
            device.status = [dic[@"responsestatus"] intValue];
        
            NSValue * value = [NSValue valueWithBytes:&device objCType:@encode(wis_user_dev)];
            if (![GlobalInfo sharedInstance].remoteArray) {
                [GlobalInfo sharedInstance].remoteArray = [NSMutableArray array];
            }
            [[GlobalInfo sharedInstance].remoteArray addObject:value];
            //DLog(@"- (void)connected %d", [GlobalInfo sharedInstance].remoteArray.count);
            
            [self storeDeviceConnectedArchiveCoder];
            
        }
        
        //更新界面
        [localArray removeObjectAtIndex:self.currentSelected.row];
        
        //[_tableView beginUpdates];
        
        //[_tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:self.currentSelected] withRowAnimation:UITableViewRowAnimationFade];
        
        self.currentSelected = nil;
        self.lastSelected = nil;
        
        //[_tableView endUpdates];
        
        
        [_tableView reloadData];
    }

}

-(void)disConnectButtonPressed
{
    if(self.currentSelected.row >= [[GlobalInfo sharedInstance].remoteArray count]) return;
    
    @synchronized([GlobalInfo sharedInstance].remoteArray)
    {
        NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:self.currentSelected.row];
        wis_user_dev device;
        [value getValue:&device];
        
        [WISInterfaces wis_send_unbind_cmd:[GlobalInfo sharedInstance].m_CmdSock uuid:device.uuid];
        
        //更新界面
        
        [[GlobalInfo sharedInstance].remoteArray removeObjectAtIndex:self.currentSelected.row];
        [self storeDeviceConnectedArchiveCoder];
            
            
        [_tableView beginUpdates];
        
        [_tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:self.currentSelected] withRowAnimation:UITableViewRowAnimationFade];
        
        self.currentSelected = nil;
        self.lastSelected = nil;
        
        [_tableView endUpdates];
        
        [self refreshUpnpStatus];
    }
}

-(void)changeNameButtonPressed
{
    NSLog(@"changeNameButtonPressed");
    
    //MulitySettingViewController *setTB = [[MulitySettingViewController alloc] init];
    
    SettingsViewController *setTB = [[SettingsViewController alloc] init];
    
    setTB.delegate = self;
    NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:self.currentSelected.row];
    setTB.value = value;
    setTB.indexPath = self.currentSelected;
    [self.navigationController pushViewController:setTB animated:YES];
}

- (UIView*)connectWithAlertView:(UIView*)view
{
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 133)];
    
    UILabel *connectlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20,280 , 22)];
    connectlabel.text = @"关联";
    connectlabel.textAlignment = UITextAlignmentCenter;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(37, 56, 56, 22)];
    nameLabel.text = @"用户名:";
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(54, 92, 73, 22)];
    userNameLabel.text = @"密码:";
    [view addSubview:nameLabel];
    [view addSubview:connectlabel];
    [view addSubview:userNameLabel];

    connectUserNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 56, 145, 22)];
    connectUserNameTextField.borderStyle = UITextBorderStyleBezel;
    connectUserNameTextField.delegate = self;
    connectPassWordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 92, 145, 22)];
    connectPassWordTextField.borderStyle = UITextBorderStyleBezel;
    connectPassWordTextField.delegate = self;
    [view addSubview:connectPassWordTextField];
    [view addSubview:connectUserNameTextField];
    return view;
}

-(void)remoteControlButtonPressed
{
    NSLog(@"%@",self.currentSelected);
    NSString *deviceUUID;
    if (self.currentSelected.section == 0)
    {
        NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:self.currentSelected.row];
        wis_user_dev device;
        [value getValue:&device];
        
        deviceUUID = [NSString stringWithFormat:@"%s",device.uuid];
    }
    else
    {
        NSDictionary *localDic = [localArray objectAtIndex:self.currentSelected.row];
        deviceUUID = localDic[@"uuid"];
    }
    
   
    if (![[GlobalService sharedInstance].curOperationDeviceUUID isEqualToString:deviceUUID]) {
        [[CMDDataProcessor sharedInstance] clearDeviceListData];
    }
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:deviceUUID forKey:@"device"];
    [GlobalService sharedInstance].curOperationDeviceUUID = deviceUUID;
    
    [self.navigationController popToRootViewControllerAnimated:YES];

    /*
    RemoteControlViewController * controller = [[RemoteControlViewController alloc] initWithNibName:@"RemoteControlViewController" bundle:nil];
    controller.uuid = [NSString stringWithFormat:@"%s",device.uuid];
    
    controller.delegate = self;
    [self.navigationController pushViewController:controller animated:YES];
    */
}

#pragma mark - public methods
-(void)remoteDeviceHasReached:(wis_user_dev_list *)remoteList
{
    int countArr[32]={0};
    BOOL needToRefreshUpnp = NO;
    NSLog(@"remoteDeviceHasReached");
    for(int i = 0; i < remoteList->num; ++i)
    {
        wis_user_dev * remoteDev = &remoteList->devs[i];
        BOOL isExsit = NO;
        for(int j = 0; j < [[GlobalInfo sharedInstance].remoteArray count]; j++)
        {
            NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:j];
            wis_user_dev device;
            [value getValue:&device];
            //NSLog(@"remoteDevId:%s status:%ld   devId:%s status:%ld", remoteDev->uuid, remoteDev->status, device.uuid, device.status);
            //存在 更新状态
            if(strcmp(remoteDev->uuid, device.uuid) == 0)
            {
                isExsit = YES;
                if(remoteDev->status != device.status)
                {
                    NSValue * value = [NSValue valueWithBytes:remoteDev objCType:@encode(wis_user_dev)];
                    [[GlobalInfo sharedInstance].remoteArray replaceObjectAtIndex:j withObject:value];
                    
                    if(remoteDev->status == 0)
                    {
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopRemoteControl" object:[NSString stringWithFormat:@"%s",device.uuid]];
                    }
                }
                
                countArr[j]=1;
                
                break;
            }
        }
        
        //增加
        if(isExsit == NO)
        {
            NSValue * value = [NSValue valueWithBytes:remoteDev objCType:@encode(wis_user_dev)];
            [[GlobalInfo sharedInstance].remoteArray addObject:value];
            
            countArr[[[GlobalInfo sharedInstance].remoteArray count]-1]=1;
            
            needToRefreshUpnp = YES;
        }
    }
    
    //删除服务器少的
    NSMutableArray * deleteArr = [NSMutableArray array];
    for(int j = 0; j < [[GlobalInfo sharedInstance].remoteArray count]; j++)
    {
        if(countArr[j] == 0)//没匹配到，说明服务器列表少了
        {
            [deleteArr addObject:[[GlobalInfo sharedInstance].remoteArray objectAtIndex:j]];
            needToRefreshUpnp = YES;
        }
    }
    
    for(NSValue * value in deleteArr)
    {
        wis_user_dev device;
        [value getValue:&device];
        
        NSLog(@"remote Reached Name:%s devId:%s", device.name, device.uuid);
        NSLog(@"sharedInstance].remoteArray removeObject: ");
        [[GlobalInfo sharedInstance].remoteArray removeObject:value];
    }
    
    if(needToRefreshUpnp == YES)
    {
        [self refreshUpnpStatus];
    }
    else
    {
        [self reloadTableView];
    }
    
    //发送消息给远程控制界面，发送早会造成提前刷新table
    for(NSValue * value in deleteArr)
    {
        wis_user_dev device;
        [value getValue:&device];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopRemoteControl" object:[NSString stringWithFormat:@"%s",device.uuid]];
    }
}

#pragma mark - private methods
-(void)refreshUpnpStatus
{
    [localArray removeAllObjects];
    
    for(NSDictionary * dic in [GlobalInfo sharedInstance].upnpArray)
    {
        NSRange endRange = [dic[@"baseURL"] rangeOfString:@":" options:NSBackwardsSearch];
        
        if(endRange.location == NSNotFound)
        {
            return;
        }
        
        NSString * baseUrl = [dic[@"baseURL"] substringToIndex:endRange.location];
        [[GlobalService sharedInstance] getDeviceInfo:self url:baseUrl];
    }
}

-(void)serviceGetDeviceInfoCallBack:(NSDictionary*)dicCallBack
{
    NSDictionary *dic = dicCallBack;
    NSLog(@"dic:%@",dic);
    
    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] != 1)
    {
        return;
    }
    
    if([[dic objectForKey:@"expired"] intValue] == 1)
    {
        return;
    }
    
    NSString * uuid = [dicCallBack objectForKey:@"uuid"];
    
    BOOL isConnected = NO;
    
    for(int j = 0; j < [[GlobalInfo sharedInstance].remoteArray count]; j++)
    {
        NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:j];
        wis_user_dev device;
        [value getValue:&device];
        
        //存在 更新状态
        NSString * remoteuuid = [NSString stringWithFormat:@"%s",device.uuid];
        if([uuid rangeOfString:remoteuuid].location != NSNotFound)
        {
            isConnected = YES;
            break;
        }
    }
    
    if(isConnected == NO)
    {
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:dicCallBack];
        NSString * version = [dic objectForKey:@"firmware"];
        NSArray * array = [version componentsSeparatedByString:@"."];
        
        int bigVersion = [array count] < 3?0:[[array objectAtIndex:[array count] - 3] intValue];
        
        [dic setObject:[NSNumber numberWithInt:bigVersion] forKey:@"bigVersion"];
        
        BOOL isExsit = NO;
        for(NSDictionary * aDic in localArray)
        {
            if([[aDic objectForKey:@"uuid"] isEqualToString:[dic objectForKey:@"uuid"]])
            {
                isExsit = YES;
                break;
            }
        }
        
        if(isExsit == NO)
        {
            [localArray addObject:dic];
            [self reloadTableView];
        }
    }
}

-(void)reloadTableView
{
    if(canRefreshData == NO) return;
    
    if(reloadWithAnimation == NO)
    {
        [_tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    }
    else
    {
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [_tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        });
    }
}

-(void)animateExpandMethod:(DemoUpnpCell *)cell
{
     NSLog(@"animateExpandMethod%@",self.currentSelected);
    NSIndexPath * cellIndex = [_tableView indexPathForCell:cell];
    self.lastSelected = self.currentSelected;
    
    if(self.currentSelected != nil && cellIndex.section == self.currentSelected.section && cellIndex.row == self.currentSelected.row)
    {
        self.currentSelected = nil;
    }
    else
    {
        self.currentSelected = cellIndex;
    }
    
    DemoUpnpCell * lastCell = (DemoUpnpCell *)[_tableView cellForRowAtIndexPath:self.lastSelected];
    if(lastCell == nil) self.lastSelected = nil;
    
    reloadWithAnimation = YES;
    
//    [_tableView beginUpdates];
//    
//    NSMutableArray * array = [NSMutableArray array];
//    if(self.currentSelected != nil)
//    {
//        [array addObject:self.currentSelected];
//    }
//    if(self.lastSelected != nil)
//    {
//        [array addObject:self.lastSelected];
//    }
//    
//    [_tableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
//    
//    [_tableView endUpdates];
    [_tableView reloadData];
}

#pragma mark - RemoteControlDelegate
-(void)clearAllDevices
{
    [localArray removeAllObjects];
    [[GlobalInfo sharedInstance].remoteArray removeAllObjects];
    
    [WISInterfaces wis_send_get_devices_cmd:[GlobalInfo sharedInstance].m_CmdSock];
}

//#pragma mark - UIAlertViewDelegate
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (alertView.tag == 100) {
//        UITextField *firstText = [alertView textFieldAtIndex:0];
//        NSString *string = [[NSString alloc] init];
//        if (buttonIndex == 1) {
//            string = firstText.text;
//            if ([string isEqualToString:@"123"]) {
//                UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"关联" message:@"关联成功" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
//                [al show];
//                [self connected];
//            }
//        }
//    }
//}

#pragma mark - CustomIOS7Delegate
- (void)customIOS7dialogButtonTouchUpInside:(id)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%ld",(long)buttonIndex);
    NSLog(@"%ld",(long)[alertView tag]);
    if ([alertView tag] == 10000)
    {
        if (buttonIndex == 1)
        {
            NSLog(@"name:%@ user:%@ password:%@",nameTextField.text,userNameTextField.text,passwordTextField.text);
        }
    }
    else
    {
        if (buttonIndex == 1)
        {
            NSLog(@"connectName:%@,connectPassword:%@",connectUserNameTextField.text,connectPassWordTextField.text);
            
            if ([connectPassWordTextField.text length] > 0 && [connectUserNameTextField.text length] > 0)
            {
                NSDictionary *dic = [localArray objectAtIndex:self.currentSelected.row];
              
                ipUrl = dic[@"sendBaseURL"];
              
                if (ipUrl)
                {
                    NSString *str = [NSString stringWithFormat:@"%@/cgi-bin/User.cgi?action=do_check&user=%@&passwd=%@",ipUrl,connectUserNameTextField.text,connectPassWordTextField.text];
                    NSString * encodingString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"encodingString：%@",encodingString);
                    
                    [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSLog(@"userResponeObject:%@",responseObject);
                        
                        if([responseObject[@"state"] isEqualToString:@"Success"])
                        {
                            //更新界面
                            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"关联设备成功" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
                            [alertView show];
                            [self connected];
                        }
                        else
                        {
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:@"输入账号密码错误" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
                            [alert show];
                        }
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"error:%@",error);
                    }];
                }
                
            }else
            {
                NSLog(@"输入账号密码错误");
            }
        }
    }
    [alertView close];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [nameTextField resignFirstResponder];
    [userNameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    [connectPassWordTextField resignFirstResponder];
    [connectUserNameTextField resignFirstResponder];
    return YES;
}

#pragma mark - 
- (void)unConnectDevice:(char *)uuid
{
    if(self.currentSelected.row >= [[GlobalInfo sharedInstance].remoteArray count]) return;
    
    @synchronized([GlobalInfo sharedInstance].remoteArray)
    {
        [WISInterfaces wis_send_unbind_cmd:[GlobalInfo sharedInstance].m_CmdSock uuid:uuid];
        
        //更新界面
        
        [[GlobalInfo sharedInstance].remoteArray removeObjectAtIndex:self.currentSelected.row];
        
        [_tableView beginUpdates];
        
        [_tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:self.currentSelected] withRowAnimation:UITableViewRowAnimationFade];
        
        self.currentSelected = nil;
        self.lastSelected = nil;
        
        [_tableView endUpdates];
        
        [self refreshUpnpStatus];
    }
}

- (void)changeName:(NSString *)nameString
{
    @synchronized([GlobalInfo sharedInstance].remoteArray)
    {
        NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:self.currentSelected.row];
        wis_user_dev device;
        [value getValue:&device];
        const char * a =[nameString UTF8String];
        memcpy(device.name, a, 32);
        NSValue *reValue = [NSValue valueWithBytes:&device objCType:@encode(wis_user_dev)];
        [[GlobalInfo sharedInstance].remoteArray replaceObjectAtIndex:self.currentSelected.row withObject:reValue];
        [self.tableView reloadData];
    }
}

#pragma mark -
- (void)storeDeviceConnectedArchiveCoder {
    
    NSString *filePath = [GlobalVar getFilePath:@"remoteDeviceArray.plist"];
    NSMutableArray *archiveCoderList = [[NSMutableArray alloc] init];
    for (NSValue *valObj in [GlobalInfo sharedInstance].remoteArray) {
        
        wis_user_dev device;
        [valObj getValue:&device];
        
        NSString *uuidStr = nil;
        NSString *nameStr = nil;
        NSString *bindTimeStr = nil;
        
        ArchiveCoderRomoteDevice *archiveCoder = [[ArchiveCoderRomoteDevice alloc] init];
        
        if (device.uuid) {
            
            uuidStr = [[NSString alloc] initWithCString:device.uuid encoding:NSUTF8StringEncoding];
            archiveCoder.uuid = uuidStr;
        }
        
        if (device.name) {
            
            nameStr = [[NSString alloc] initWithCString:device.name encoding:NSUTF8StringEncoding];
            archiveCoder.name = nameStr;
        }
        
        if (device.bind_time) {
            
            bindTimeStr = [[NSString alloc] initWithCString:device.bind_time encoding:NSUTF8StringEncoding];
            archiveCoder.bindTime = bindTimeStr;
        }
        
        archiveCoder.status = device.status;
        [archiveCoderList addObject:archiveCoder];
    }
    
    [NSKeyedArchiver archiveRootObject:archiveCoderList toFile:filePath];
    
    NSLog(@"applicationWillResignActive %ld", archiveCoderList.count);
    
}


@end
